package com.trsj.lnsj.config;

import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.trsj.lnsj.common.DataResponse;
import com.trsj.lnsj.common.MsgStatus;
import com.trsj.lnsj.util.JWTHelper;

/**  

* <p>Title: TokenInterceptor.java</p>  

* <p>Description: </p>  

* <p>Copyright: Copyright (c) 2018</p>  

* <p>Company: 七色环</p>  

* @author longky  

* @date 2018年9月1日  

* @version 1.0  

*/
public class JWTInterceptor implements HandlerInterceptor  {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		String JWT_Header=request.getHeader("JWT");
		String URL_Header=request.getParameter("JWT");
		if(StringUtils.isEmpty(JWT_Header)&&!StringUtils.isEmpty(URL_Header)) {
			
			JWT_Header=URL_Header;
		}
	    Map<String,Object> info=JWTHelper.parseJavaWebToken(JWT_Header, "zlnsj");
	    if(info==null) {
	    	DataResponse dataResponse=new DataResponse(MsgStatus.TOKEN_FAILED);
	    	sendMessage(response,dataResponse);
	    	return false;
	    }
	    if(info.get("userid")==null) {
	    	return false;
	    }
	    return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
	
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	  public static void sendMessage(HttpServletResponse response, DataResponse data) throws Exception {
	        response.setContentType("text/html; charset=utf-8");
	        PrintWriter writer = response.getWriter();
	        String json=JSON.toJSONString(data);
	        writer.print(json);
	        writer.close();
	        response.flushBuffer(); 
	    }
}

